import time
import smbus    # 这是一个读取I2C地址的工具

BUS = smbus.SMBus(1)    # 创建一个smbus实例0 代表 /dev/i2c-0， 1 代表 /dev/i2c-1
LCD_ADDR = 0x27         # LCD的I2C地址
BLEN = 1


def turn_light(key):
    global BLEN
    BLEN = key
    if key == 1:
        BUS.write_byte(LCD_ADDR, 0x08)
    else:
        BUS.write_byte(LCD_ADDR, 0x00)


def write_word(addr, data):
    global BLEN
    temp = data
    if BLEN == 1:
        temp |= 0x08
    else:
        temp &= 0xF7
    BUS.write_byte(addr, temp)


def send_command(comm):
    # Send bit7-4 firstly
    buf = comm & 0xF0
    buf |= 0x04  # RS = 0, RW = 0, EN = 1
    write_word(LCD_ADDR, buf)
    time.sleep(0.002)
    buf &= 0xFB  # Make EN = 0
    write_word(LCD_ADDR, buf)

    # Send bit3-0 secondly
    buf = (comm & 0x0F) << 4
    buf |= 0x04  # RS = 0, RW = 0, EN = 1
    write_word(LCD_ADDR, buf)
    time.sleep(0.002)
    buf &= 0xFB  # Make EN = 0
    write_word(LCD_ADDR, buf)


def send_data(data):
    # Send bit7-4 firstly
    buf = data & 0xF0
    buf |= 0x05  # RS = 1, RW = 0, EN = 1
    write_word(LCD_ADDR, buf)
    time.sleep(0.002)
    buf &= 0xFB  # Make EN = 0
    write_word(LCD_ADDR, buf)

    # Send bit3-0 secondly
    buf = (data & 0x0F) << 4
    buf |= 0x05  # RS = 1, RW = 0, EN = 1
    write_word(LCD_ADDR, buf)
    time.sleep(0.002)
    buf &= 0xFB  # Make EN = 0
    write_word(LCD_ADDR, buf)


def init_lcd():
    """
    LCD的初始化程序
    :return:
    """
    try:
        send_command(0x33)  # Must initialize to 8-line mode at first
        time.sleep(0.005)
        send_command(0x32)  # Then initialize to 4-line mode
        time.sleep(0.005)
        send_command(0x28)  # 2 Lines & 5*7 dots
        time.sleep(0.005)
        send_command(0x0C)  # Enable display without cursor
        time.sleep(0.005)
        send_command(0x01)  # Clear Screen
    except:
        return False
    else:
        return True


def clear_lcd():
    """
    清空屏幕程序包括背景灯
    :return:
    """
    send_command(0x01)  # Clear Screen


def print_lcd(x, y, Str):
    """
    这是一个主要的LCD输出打印程序
    :param x: 横坐标
    :param y: 纵坐标
    :param Str: 输出文字
    :return:
    """
    if x < 0:
        x = 0
    if x > 15:
        x = 15
    if y < 0:
        y = 0
    if y > 1:
        y = 1

    # Move cursor
    addr = 0x80 + 0x40 * y + x
    send_command(addr)

    for Chr in Str:
        send_data(ord(Chr))


# if __name__ == '__main__':
